package com.yuncheng.spcyApi.spcy;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.busService.InitWjjlService;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.wjml.WjmlConstant;
import com.yuncheng.spcyApi.constant.xcjchy.SqsxHyConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.spcyService.*;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.spcyApi.vo.common.HttpResultVo;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.jcy.HcyXpVo;
import com.yuncheng.spcyApi.vo.sqsx.SqsxXpryNumVo;
import com.yuncheng.spcyApi.vo.xcjchy.SqsxHyHtmlConvertVo;
import com.yuncheng.spcyApi.vo.xcjchy.SqsxHyVo;
import com.yuncheng.vo.HttpResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

/**
 * @author hua
 */
@Api(tags = "申请事项-业务相关信息")
@RestController
@RequestMapping("/api/spzx-spcy/sqsxYwxx")
public class SpcySqsxYwxxController {
    private static final Logger log = LoggerFactory.getLogger(SpcySqsxYwxxController.class);

    @Resource
    private XpryTimedTasksService xpryTimedTasksService;

    @Resource
    private ISpcySqsxHyztService spcySqsxHyztService;

    @Resource
    private ISpcySqsxHymxService spcySqsxHymxService;

    @Resource
    private ZdyUploadFileService zdyUploadFileService;

    @Resource
    private ISpcySqsxXpjlService spcySqsxXpjlService;

    @Resource
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private ISysUserCyyjService sysUserCyyjService;

    @Resource
    private InitWjjlService initWjjlService;

    @Resource
    private ISpcySqsxWjjlService spcySqsxWjjlService;

    @Resource
    private SqsxYwxxInfoService sqsxYwxxInfoService;

    @Autowired
    @Qualifier("asyncNormalTask")
    private Executor executor;

    @Log(title = "添加自动抽选人员定时任务")
    @ApiOperation(value = "添加自动抽选人员定时任务")
    @PostMapping(value = "initDsrwAutoXpry")
    public HttpResult initDsrwAutoXpry(@RequestBody HcyXpVo bean){
        // 接口限流
        if (!IpRateLimiterUtils.tryAcquire(GetCurrentUserUtils.getCurrentUserId())){
            return HttpResult.error("访问过于频繁，请稍候再试！");
        }

        bean.setFsmszt("是");
        xpryTimedTasksService.initAutoXpryYwxx(bean);

        return HttpResult.ok("操作成功");
    }

    @Log(title = "获取已选派人员的数量及状态")
    @ApiOperation(value = "获取已选派人员的数量及状态")
    @GetMapping(value = "getYxprySlhzt")
    public HttpResult getYxprySlhzt(@RequestParam(value = "sqsxid",defaultValue = "")String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("参数为空！");
        }

        SqsxXpryNumVo numVo = xpryTimedTasksService.getYxprySlhzt(sqsxid);
        numVo = xpryTimedTasksService.getTyxprySlhzt(sqsxid, numVo);

        return HttpResult.ok(numVo);
    }

    /*@Log(title = "申请事项-将选派人员组长变为组员")
    @ApiOperation(value = "申请事项-将选派人员组长变为组员")*/
    @PostMapping(value = "updateXp")
    public HttpResult updateXp(@RequestBody SpcySqsxXpjl parVo){
        if (StringUtils.isBlank(parVo.getId())){
            return HttpResult.error("参数为空！");
        }

        Result result = xpryTimedTasksService.updateXpJcySskByZzToZy(parVo.getId());
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }

        return HttpResult.ok("操作成功");
    }

    @Log(title = "获取发送检查通知短信的内容")
    @ApiOperation(value = "获取发送检查通知短信的内容")
    @GetMapping(value = "getJctzSmsContent")
    public HttpResult getJctzSmsContent(@RequestParam(value = "sqsxid",defaultValue = "")String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("参数为空！");
        }

        String msg = xpryTimedTasksService.genJctzSmsContent(sqsxid);

        return HttpResultVo.HttpResultSave(msg, "操作成功");
    }

    @Log(title = "获取发送检查通知短信的人员信息")
    @ApiOperation(value = "获取发送检查通知短信的人员信息")
    @GetMapping(value = "getJctzSmsRyxx")
    public HttpResult getJctzSmsRyxx(@RequestParam(value = "sqsxid",defaultValue = "")String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("参数为空！");
        }

        // 获取能够发送检查通知短信的人员列表
        List<SpcySqsxXpjl> wqrList = spcySqsxXpjlService.getTyXpXpjlListNotOrder(sqsxid);

        String msg = "";
        String zz = "";
        String zy = "";
        String yb = "";
        for (int i=0; i<wqrList.size(); i++){
            if (wqrList.get(i).getFssk().equals(SpcyConstant.HCY_SSK_ZZ)){
                zz += StringUtils.isNotBlank(zz) ? "、" : "";
                zz += wqrList.get(i).getFjcyxm() + "("+wqrList.get(i).getFgzdw()+" "+ wqrList.get(i).getFjcylxdh()+")";

            }else if (wqrList.get(i).getFssk().equals(SpcyConstant.HCY_SSK_ZY)){
                zy += StringUtils.isNotBlank(zy) ? "、" : "";
                zy += wqrList.get(i).getFjcyxm() + "("+wqrList.get(i).getFgzdw()+" "+ wqrList.get(i).getFjcylxdh()+")";

            }else if (wqrList.get(i).getFssk().equals(SpcyConstant.HCY_SSK_YB)){
                yb += StringUtils.isNotBlank(yb) ? "、" : "";
                yb += wqrList.get(i).getFjcyxm() + "("+wqrList.get(i).getFgzdw()+" "+ wqrList.get(i).getFjcylxdh()+")";

            }
        }

        msg += StringUtils.isNotBlank(zz) ? "组长：" + zz : "";

        if (StringUtils.isNotBlank(zy)){
            msg += StringUtils.isNotBlank(msg) ? "\n" : "";
            msg += "组员：" + zy;
        }

        if (StringUtils.isNotBlank(yb)){
            msg += StringUtils.isNotBlank(msg) ? "\n" : "";
            msg += "预备检查员：" + yb;
        }

        return HttpResultVo.HttpResultSave(msg, "操作成功");
    }

    @Log(title = "获取抽选人员-发送待确认短信内容")
    @ApiOperation(value = "获取抽选人员-发送待确认短信内容")
    @GetMapping(value = "getCxrySendDqrSmsNr")
    public HttpResult getCxrySendDqrSmsNr(@RequestParam(value = "sqsxid",defaultValue = "")String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("参数为空！");
        }

        String msg = sysUserCyyjService.getCyyjContent(sqsxid, sqsxid);
        if (StringUtils.isBlank(msg)) {
            msg = xpryTimedTasksService.genXprySendSmsNew(null, null, sqsxid);
        }

        return HttpResultVo.HttpResultSave(msg, "操作成功");
    }

    @Log(title = "获取抽选人员-发送待确认人员信息")
    @ApiOperation(value = "获取抽选人员-发送待确认人员信息")
    @GetMapping(value = "getCxrySendDqrRyxx")
    public HttpResult getCxrySendDqrRyxx(@RequestParam(value = "sqsxid",defaultValue = "")String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("参数为空！");
        }

        // 获取没有发送短信的待确认人员列表
        List<SpcySqsxXpjl> wqrList = spcySqsxXpjlService.getDqrXpjlNotSendSmsztList(sqsxid);
        String zz = "";
        String zy = "";
        String yb = "";
        for (int i=0; i<wqrList.size(); i++){
            if (wqrList.get(i).getFssk().equals(SpcyConstant.HCY_SSK_ZZ)){
                zz += StringUtils.isNotBlank(zz) ? "、" : "";
                zz += wqrList.get(i).getFjcyxm() + "("+wqrList.get(i).getFgzdw()+" "+ wqrList.get(i).getFjcylxdh()+")";

            }else if (wqrList.get(i).getFssk().equals(SpcyConstant.HCY_SSK_ZY)){
                zy += StringUtils.isNotBlank(zy) ? "、" : "";
                zy += wqrList.get(i).getFjcyxm() + "("+wqrList.get(i).getFgzdw()+" "+ wqrList.get(i).getFjcylxdh()+")";

            }else if (wqrList.get(i).getFssk().equals(SpcyConstant.HCY_SSK_YB)){
                yb += StringUtils.isNotBlank(yb) ? "、" : "";
                yb += wqrList.get(i).getFjcyxm() + "("+wqrList.get(i).getFgzdw()+" "+ wqrList.get(i).getFjcylxdh()+")";

            }
        }

        String msg = "";
        msg += StringUtils.isNotBlank(zz) ? "组长：" + zz : "";

        if (StringUtils.isNotBlank(zy)){
            msg += StringUtils.isNotBlank(msg) ? "\n" : "";
            msg += "组员：" + zy;
        }

        if (StringUtils.isNotBlank(yb)){
            msg += StringUtils.isNotBlank(msg) ? "\n" : "";
            msg += "预备检查员：" + yb;
        }

        /*if (StringUtils.isBlank(msg)){
            msg = "没有需要发送短信的人员！";
        }*/

        return HttpResultVo.HttpResultSave(msg, "操作成功");
    }

    @Log(title = "保存抽选人员-发送待确认短信内容")
    @ApiOperation(value = "保存抽选人员-发送待确认短信内容")
    @PostMapping(value = "saveCxrySendDqrSmsNr")
    public HttpResult saveCxrySendDqrSmsNr(@RequestBody HcyXpVo bean){
        if (StringUtils.isBlank(bean.getSqsxid())){
            return HttpResult.error("事项参数为空！");
        }

        if (StringUtils.isBlank(bean.getFdqrdxnr())){
            return HttpResult.error("内容为空！");
        }
        List<SysUserCyyj> cyyjList = sysUserCyyjService.getCyyjList(bean.getSqsxid(), bean.getSqsxid());
        if (CollectionUtil.isEmpty(cyyjList)){
            sysUserCyyjService.addCyyj(bean.getSqsxid(), bean.getSqsxid(), "待确认短信模板", bean.getFdqrdxnr());
        }else {
            sysUserCyyjService.updateCyyj(bean.getSqsxid(), bean.getSqsxid(), bean.getFdqrdxnr());
        }

        return HttpResult.ok("保存成功");
    }

    @Log(title = "单个发送确认短信-选派人员")
    @ApiOperation(value = "单个发送确认短信-选派人员")
    @PostMapping(value = "sendQrSmsSingle")
    public HttpResult sendQrSmsSingle(@RequestBody HcyXpVo bean){
        if (StringUtils.isBlank(bean.getId())){
            return HttpResult.error("选派参数为空！");
        }
        if (StringUtils.isBlank(bean.getFdqrdxnr())){
            return HttpResult.error("短信内容为空！");
        }

        xpryTimedTasksService.sendQrSmsSingle(bean.getId(), bean.getFdqrdxnr());

        return HttpResult.ok("发送成功");
    }

    @Log(title = "发送确认短信-选派人员-批量发送")
//    @ApiOperation(value = "发送确认短信-选派人员-批量发送")
    @PostMapping(value = "sendQrSms")
    public HttpResult sendQrSmsBatch(@RequestBody HcyXpVo bean){

        if (StringUtils.isBlank(bean.getSqsxid())){
            return HttpResult.error("事项参数为空！");
        }

//        xpryTimedTasksService.autoCommonSendDqrSms(bean.getIds(), bean.getSqsxid(), bean.getFdqrdxnr());
        return HttpResult.ok("发送成功");
    }

    @Log(title = "获取预报名抽选人员-发送待确认短信内容")
    @ApiOperation(value = "获取预报名抽选人员-发送待确认短信内容")
    @GetMapping(value = "getYbmCxrySendDqrSmsNr")
    public HttpResult getYbmCxrySendDqrSmsNr(@RequestParam(value = "sqsxid",defaultValue = "")String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("参数为空！");
        }

        return HttpResultVo.HttpResultSave("", "操作成功");
    }

    @Log(title = "获取申请事项-自动抽选人员任务列表")
    @ApiOperation(value = "获取申请事项-自动抽选人员任务列表")
    @GetMapping(value = "queryAutoXpryYwxxList")
    public HttpResult queryAutoXpryYwxxList(@RequestParam(value = "sqsxid",defaultValue = "")String sqsxid){

        return HttpResultVo.HttpResultList(xpryTimedTasksService.queryAutoXpryYwxxList(sqsxid));
    }

    @Log(title = "验证申请事项是否存在执行中自动抽选人员任务")
    @ApiOperation(value = "验证申请事项是否存在执行中自动抽选人员任务(true: 有执行中)")
    @GetMapping(value = "verifyAutoXpryYwxxIsExists")
    public HttpResult verifyAutoXpryYwxxIsExists(@RequestParam(value = "sqsxid",defaultValue = "")String sqsxid){

        return xpryTimedTasksService.verifyAutoXpryYwxxIsExists(sqsxid);
    }

    @Log(title = "提前结束-执行中的自动抽选任务列表")
    @ApiOperation(value = "提前结束-执行中的自动抽选任务列表")
    @GetMapping(value = "tjEndZxzAutoXpryRwList")
    public HttpResult tjEndZxzAutoXpryRwList(@RequestParam(value = "sqsxid",defaultValue = "")String sqsxid){

        xpryTimedTasksService.tjEndZxzAutoXpryRwList(sqsxid);
        return HttpResult.ok("操作成功");
    }

    @Log(title = "申请事项会议-列表查询")
    @ApiOperation(value = "申请事项会议-列表查询")
    @GetMapping(value = "querySqsxHyPageList")
    public HttpResult querySqsxHyPageList(@RequestParam(value = "sqsxid",defaultValue = "") String sqsxid,
                                          @RequestParam(value = "fhylx",defaultValue = "") String fhylx,
                                          @RequestParam(value = "gjz",defaultValue = "") String gjz){
        if (StringUtils.isBlank(sqsxid)){
            sqsxid = "0";
        }

        LambdaQueryWrapper<SpcySqsxHyzt> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcySqsxHyzt::getFsqsxid, sqsxid);
        queryWrapper.eq(StringUtils.isNotBlank(fhylx), SpcySqsxHyzt::getFhylx, fhylx);

        if (StringUtils.isNotBlank(gjz)){
            queryWrapper
                    .and(q->q.like(SpcySqsxHyzt::getFhyzt, gjz)
                    .like(SpcySqsxHyzt::getFhydd, gjz));
        }

        queryWrapper.orderByAsc(SpcySqsxHyzt::getFhysj);

        List<SpcySqsxHyzt> pageList = spcySqsxHyztService.list(queryWrapper);
        return HttpResultVo.HttpResultList(pageList);
    }

//    @Log(title = "申请事项会议-打印信息")
//    @ApiOperation(value = "申请事项会议-打印信息")
    @GetMapping(value = "querySqsxHyPrintInfo")
    public HttpResult querySqsxHyPrintInfo(@RequestParam(value = "sqsxid",defaultValue = "0")String sqsxid){

        return HttpResult.ok();
    }

    @Log(title = "申请事项会议-会议签到-打印信息")
    @ApiOperation(value = "申请事项会议-会议签到-打印信息")
    @GetMapping(value = "queryHyqdPrintInfo")
    public HttpResult queryHyqdPrintInfo(@RequestParam(value = "sqsxid",defaultValue = "0")String sqsxid){

        Map resultMap = new HashMap();

        SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
        resultMap.put("sqsx", sqsx);

        // 会议
        CompletableFuture<String> futureHy = CompletableFuture.supplyAsync(() -> {

            List<SpcySqsxHyzt> hyList = spcySqsxHyztService.list(new LambdaQueryWrapper<SpcySqsxHyzt>()
                    .eq(SpcySqsxHyzt::getFsqsxid, sqsxid)
                    .orderByAsc(SpcySqsxHyzt::getFhysj));

            List<SpcySqsxHyzt> schyList = hyList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getFhylx()) && f.getFhylx().equals(SqsxHyConstant.HYLX_SCHY))
                    .collect(Collectors.toList());

            List<SpcySqsxHyzt> mxhyList = hyList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getFhylx()) && f.getFhylx().equals(SqsxHyConstant.HYLX_MCHY))
                    .collect(Collectors.toList());

            Map schyMap = sqsxYwxxInfoService.getHyqdPrintInfo(schyList);
            Map mchyMap = sqsxYwxxInfoService.getHyqdPrintInfo(mxhyList);

            resultMap.put("schy", schyMap);
            resultMap.put("mchy", mchyMap);

            return "1";
        }, executor);

        /** 等待所有结果执行完成 */
        try {
            CompletableFuture.allOf(futureHy).get();
        } catch (InterruptedException e) {
            log.error("[InterruptedException]申请事项会议-打印信息: {}", e.getMessage());
        } catch (ExecutionException e) {
            log.error("[InterruptedException]申请事项会议-打印信息: {}", e.getMessage());
        }

        return HttpResult.ok(resultMap);
    }

    @Log(title = "事项首次会议-会议签到-模板转PDF绑定事项")
    @ApiOperation(value = "事项首次会议-会议签到-模板转PDF绑定事项")
    @PostMapping(value = "HtmlToFileByXcjchy")
    public HttpResult HtmlToFileByXcjchy(@RequestBody SqsxHyHtmlConvertVo query){
        if (StringUtils.isBlank(query.getSqsxid())){
            return HttpResult.error("事项参数为空！");
        }

        List<SpcySqsxHyzt> hyList = spcySqsxHyztService.list(new LambdaQueryWrapper<SpcySqsxHyzt>()
                .eq(SpcySqsxHyzt::getFsqsxid, query.getSqsxid())
                .eq(SpcySqsxHyzt::getFhylx, SqsxHyConstant.HYLX_SCHY)
                .orderByAsc(SpcySqsxHyzt::getFhysj));

        /*List<SpcySqsxHyzt> schyList = hyList.stream()
                .filter(f -> StringUtils.isNotBlank(f.getFhylx()) && f.getFhylx().equals(SqsxHyConstant.HYLX_SCHY))
                .collect(Collectors.toList());*/

        /*List<SpcySqsxHyzt> mxhyList = hyList.stream()
                .filter(f -> StringUtils.isNotBlank(f.getFhylx()) && f.getFhylx().equals(SqsxHyConstant.HYLX_MCHY))
                .collect(Collectors.toList());*/

        Map schyMap = sqsxYwxxInfoService.getHyqdPrintInfo(hyList);
//        Map mchyMap = sqsxYwxxInfoService.getHyqdPrintInfo(mxhyList);

        Result result = initWjjlService.genXcjchyqdbHtmlConvertFile(query.getSqsxid(), schyMap, null, 1);
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }

        return HttpResult.ok();
    }

    @Log(title = "下载申请事项会议-会议签到表带签字模板")
    @ApiOperation(value = "下载申请事项会议-会议签到表带签字模板")
    @PostMapping(value = "downHtmlToFileByXcjchy")
    public void downHtmlToFileByXcjchy(@RequestBody SqsxHyHtmlConvertVo query, HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(query.getSqsxid())){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("事项参数为空！");
            writer.close(); // 不要忘记关闭PrintWriter
            return;
        }

        List<SpcySqsxHyzt> hyList = spcySqsxHyztService.list(new LambdaQueryWrapper<SpcySqsxHyzt>()
                .eq(SpcySqsxHyzt::getFsqsxid, query.getSqsxid())
                .orderByAsc(SpcySqsxHyzt::getFhysj));

        List<SpcySqsxHyzt> schyList = hyList.stream()
                .filter(f -> StringUtils.isNotBlank(f.getFhylx()) && f.getFhylx().equals(SqsxHyConstant.HYLX_SCHY))
                .collect(Collectors.toList());

        List<SpcySqsxHyzt> mxhyList = hyList.stream()
                .filter(f -> StringUtils.isNotBlank(f.getFhylx()) && f.getFhylx().equals(SqsxHyConstant.HYLX_MCHY))
                .collect(Collectors.toList());

        Map schyMap = sqsxYwxxInfoService.getHyqdPrintInfo(schyList);
        Map mchyMap = sqsxYwxxInfoService.getHyqdPrintInfo(mxhyList);

        initWjjlService.downXcjchyqdbHtmlConvertFile(query.getSqsxid(), schyMap, mchyMap, 0, response);
    }

    @Log(title = "下载申请事项会议-现场检查纪律带签字模板")
    @ApiOperation(value = "下载申请事项会议-现场检查纪律带签字模板")
    @PostMapping(value = "downHtmlToFileByXcjcjl")
    public void downHtmlToFileByXcjcjl(@RequestBody SqsxHyHtmlConvertVo query, HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(query.getSqsxid())){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("事项参数为空！");
            writer.close(); // 不要忘记关闭PrintWriter
            return;
        }

        List<SpcySqsxHyzt> hyList = spcySqsxHyztService.list(new LambdaQueryWrapper<SpcySqsxHyzt>()
                .eq(SpcySqsxHyzt::getFsqsxid, query.getSqsxid())
                .eq(SpcySqsxHyzt::getFhylx, SqsxHyConstant.HYLX_SCHY)
                .orderByAsc(SpcySqsxHyzt::getFhysj));

        Map schyMap = sqsxYwxxInfoService.getHyqdPrintInfo(hyList, true);

        initWjjlService.downXcjcjlHtmlConvertFile(query.getSqsxid(), schyMap, response);
    }

    @Log(title = "申请事项会议及明细")
    @ApiOperation(value = "申请事项会议及明细")
    @GetMapping(value = "querySqsxHyInfo")
    public HttpResult querySqsxHyInfo(@RequestParam(value = "id",defaultValue = "0")String id){
        SpcySqsxHyzt hy = spcySqsxHyztService.getById(id);

        List<SpcySqsxHymx> hymxList = spcySqsxHymxService.list(new LambdaQueryWrapper<SpcySqsxHymx>()
                .eq(SpcySqsxHymx::getFhyid, id)
                .orderByAsc(SpcySqsxHymx::getCreateTime));

        Map resultMap = new HashMap();
        resultMap.put("hy", hy);
        resultMap.put("hymxList", hymxList);
        return HttpResult.ok(resultMap);
    }

    @Log(title = "申请事项会议-根据id")
    @ApiOperation(value = "申请事项会议-根据id")
    @GetMapping(value = "querySqsxHyById")
    public HttpResult querySqsxHyById(@RequestParam(value = "id",defaultValue = "0")String id){
        SpcySqsxHyzt hy = spcySqsxHyztService.getById(id);

        return HttpResult.ok(hy);
    }

    @Log(title = "申请事项会议明细-根据id")
    @ApiOperation(value = "申请事项会议明细-根据id")
    @GetMapping(value = "querySqsxHymxById")
    public HttpResult querySqsxHymxById(@RequestParam(value = "id",defaultValue = "0")String id){
        SpcySqsxHymx hy = spcySqsxHymxService.getById(id);

        return HttpResult.ok(hy);
    }

    @Log(title = "申请事项会议明细列表-根据会议id")
    @ApiOperation(value = "申请事项会议明细列表-根据会议id")
    @GetMapping(value = "querySqsxHymxListByHyId")
    public HttpResult querySqsxHymxListByHyId(@RequestParam(value = "id",defaultValue = "0")String id,
                                              @RequestParam(value = "frylx",defaultValue = "")String frylx){
        List<SpcySqsxHymx> hymxList = spcySqsxHymxService.list(new LambdaQueryWrapper<SpcySqsxHymx>()
                .eq(SpcySqsxHymx::getFhyid, id)
                .eq(StringUtils.isNotBlank(frylx), SpcySqsxHymx::getFrylx, frylx)
                .orderByAsc(SpcySqsxHymx::getFrylx)
                .orderByAsc(SpcySqsxHymx::getCreateTime));

        return HttpResultVo.HttpResultPageList(hymxList);
    }

    @Log(title = "申请事项会议签到记录-根据会议id")
    @ApiOperation(value = "申请事项会议签到记录-根据会议id")
    @GetMapping(value = "queryXchyQdjl")
    public HttpResult queryXchyQdjl(@RequestParam(value = "id",defaultValue = "0")String id){
        List<SpcySqsxHymx> hymxList = spcySqsxHymxService.list(new LambdaQueryWrapper<SpcySqsxHymx>()
                .eq(SpcySqsxHymx::getFhyid, id)
                .orderByAsc(SpcySqsxHymx::getFrylx)
                .orderByAsc(SpcySqsxHymx::getCreateTime));

        return HttpResultVo.HttpResultList(hymxList);
    }

//    @Log(title = "申请事项会议-添加")
//    @ApiOperation(value = "申请事项会议-添加")
    @PostMapping(value = "addSqsxHy")
    public HttpResult addSqsxHy(@RequestBody SqsxHyVo bean){
        // 接口限流
        if (!IpRateLimiterUtils.tryAcquire(GetCurrentUserUtils.getCurrentUserId())){
            return HttpResult.error("访问过于频繁，请稍候再试！");
        }

        if (StringUtils.isBlank(bean.getSqsxid())){
            return HttpResult.error("事项参数为空！");
        }
        if (StringUtils.isBlank(bean.getFhyzt())){
            return HttpResult.error("主题为空！");
        }
        if (StringUtils.isBlank(bean.getFhydd())){
            return HttpResult.error("地点为空！");
        }
        if (bean.getFhysj() == null){
            return HttpResult.error("时间为空！");
        }
        bean.setId(GetUuIdUtils.ReplaceUuId());
        bean.setFsqsxid(bean.getSqsxid());

        /** 初始化选派人员 */
        /*List<SpcySqsxHymx> mxList = new ArrayList<>();
        List<SpcySqsxXpjl> xpList = spcySqsxXpjlService.getTyXpXpjlList(bean.getSqsxid(), null);
        if (CollectionUtil.isNotEmpty(xpList)){
            SpcySqsxHymx newHymx = null;
            for (SpcySqsxXpjl xpjl : xpList){
                newHymx = new SpcySqsxHymx();
                newHymx.setId(GetUuIdUtils.ReplaceUuId());
                newHymx.setFhyid(bean.getId());
                newHymx.setFrylx("检查员");
                newHymx.setFxm(xpjl.getFjcyxm());
                newHymx.setFbm(xpjl.getFgzdw());
                newHymx.setFzw(xpjl.getFssk());
                newHymx.setFjcsf(xpjl.getFssk());

                String fqmfj = "";
                if (StringUtils.isNotBlank(xpjl.getFuserid())) {
                    fqmfj = spcyMyInfoService.genUserSignLink(xpjl.getFuserid());
                }

                newHymx.setFqmfj(fqmfj);
                newHymx.setFuserid(xpjl.getFuserid());
                newHymx.setCreateTime(new Date());
                newHymx.setCreateBy(GetCurrentUserUtils.getCurrentUserAccount());

                mxList.add(newHymx);
            }
        }*/

        if (StringUtils.isBlank(bean.getFhylx())){
            bean.setFhylx(SqsxHyConstant.HYLX_SCHY);
        }
        bean.setFstate(SqsxHyConstant.getHyState(1));
        boolean save = spcySqsxHyztService.save(bean);
        if (save){
            /*if (CollectionUtil.isNotEmpty(mxList)) {
                spcySqsxHymxService.saveBatch(mxList);
            }*/

            String operContent = "删除：";
            operContent += LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(bean));

            spcyLogService.addLogs(LogConstant.LOGS_SQSX_HY,operContent,bean.getFsqsxid(),"申请事项会议-添加", SpcyConstant.LOGS_SYS_TYPE_SC);

        }

        return HttpResultVo.HttpResultSave(bean.getId(), "添加成功");
    }

    @Log(title = "申请事项会议-完成登记/签到-根据会议id")
    @ApiOperation(value = "申请事项会议-完成登记/签到-根据会议id")
    @GetMapping(value = "sqsxhywc")
    public HttpResult sqsxhywc(@RequestParam(value = "id",defaultValue = "") String id){
        if (StringUtils.isBlank(id)){
            return HttpResult.error("参数为空！");
        }
        SpcySqsxHyzt hy = spcySqsxHyztService.getById(id);
        if (hy == null){
            return HttpResult.error("没有相匹配的会议数据！");
        }

        if (StringUtils.isBlank(hy.getFstate()) || hy.getFstate().equals(SqsxHyConstant.getHyState(1))){

            Result result = sqsxYwxxInfoService.sqsxHySubmit(id, hy.getFsqsxid(), hy);
            if (!result.isSuccess()){
                return HttpResult.error(result.getMessage());
            }

        }
        else if (hy.getFstate().equals(SqsxHyConstant.getHyState(2))){
            hy.setFstate(SqsxHyConstant.getHyState(3));
//            boolean flag = spcySqsxHyztService.updateHyFstate(id, SqsxHyConstant.getHyState(3));
            boolean flag = spcySqsxHyztService.updateById(hy);
            if (flag){
                sqsxYwxxInfoService.initHyQdjlTable(hy, hy.getFsqsxid(), 0);
            }
        }

        return HttpResult.ok();
    }

    @Log(title = "申请事项会议-验证企业关键人员是否已签字")
    @ApiOperation(value = "申请事项会议-验证企业关键人员是否已签字")
    @GetMapping(value = "verifyGjry")
    public HttpResult verifyGjry(@RequestParam(value = "id",defaultValue = "") String id){

        return sqsxYwxxInfoService.verifyHyQdjlQyGjry(id);
    }

    @Log(title = "获取首次会议-相关签到记录及附件")
    @ApiOperation(value = "获取首次会议-相关签到记录及附件")
    @GetMapping(value = "querySchyQdjlFj")
    public HttpResult querySchyQdjlFj(@RequestParam(value = "sqsxid",defaultValue = "") String sqsxid){

        /** 目录列表 */
        List<String> typeList = CollectionUtil.newArrayList(
                WjmlConstant.xcjcjl,
                WjmlConstant.xcjchyqdb,
                WjmlConstant.wlyctsm,
                WjmlConstant.xcjcjcycns
                );

        /** 首次会议签到记录 */
        List<SpcySqsxHymx> schyqdList = spcySqsxHyztService.selectHymxByFsqsxid(sqsxid, SqsxHyConstant.HYLX_SCHY);

        List<Map> resultMapList = new ArrayList<>();

        /** 对应目录的所有附件 */
        List<SpcySqsxWjjl> wjList = spcySqsxWjjlService.findWjjlListByFwjlx1(typeList, sqsxid);
        for (String ml : typeList){
            HashMap clmlMap = new HashMap();
            clmlMap.put("yq", ml);
            clmlMap.put("clmc", ml);

            /** 相关附件 */
            List<SpcySqsxWjjl> filterList = wjList.stream()
                    .filter(f -> f.getFwjlx1().equals(ml))
                    .collect(Collectors.toList());
            clmlMap.put("wjList", filterList);

            /** 对应目录的签到记录 */
            List<SpcySqsxHymx> qdList = new ArrayList<>();
            if (ml.equals(WjmlConstant.xcjcjl)){

                qdList = schyqdList;

                /*qdList = schyqdList.stream()
                        .filter(f->
                                    StringUtils.isNotBlank(f.getFrylx()) &&
                                (
                                    f.getFrylx().equals(SqsxHyConstant.getHymxRylx(1))
                                    ||
                                    f.getFrylx().equals(SqsxHyConstant.getHymxRylx(3))
                                )
                        )
                        .collect(Collectors.toList());*/

            }
            else if (ml.equals(WjmlConstant.xcjchyqdb)){

               /* qdList = schyList.stream()
                        .filter(f->
                                (StringUtils.isNotBlank(f.getFrylx())
                                        && f.getFrylx().equals(SqsxHyConstant.getHymxRylx(1))
                                )
                                        ||
                                        (StringUtils.isNotBlank(f.getFrylx()) && f.getFrylx().equals(SqsxHyConstant.getHymxRylx(3))
                                                && StringUtils.isNotBlank(f.getFbm())
                                                && f.getFbm().equals(SqsxHyConstant.getHymxQyRyLx(1))
                                        )
                        )
                        .collect(Collectors.toList());*/
                qdList = schyqdList;
            }
            else if (ml.equals(WjmlConstant.wlyctsm)){

                qdList = schyqdList.stream()
                        .filter(f->
                                StringUtils.isNotBlank(f.getFrylx())
                                        && f.getFrylx().equals(SqsxHyConstant.getHymxRylx(1))
                        )
                        .collect(Collectors.toList());

            }
            else if (ml.equals(WjmlConstant.xcjcjcycns)){
                qdList = schyqdList.stream()
                        .filter(f->
                                StringUtils.isNotBlank(f.getFrylx())
                                        && f.getFrylx().equals(SqsxHyConstant.getHymxRylx(1))
                        )
                        .collect(Collectors.toList());

            }
            clmlMap.put("qdList", qdList);

            resultMapList.add(clmlMap);
        }

        return HttpResult.ok(resultMapList);
    }

    @Log(title = "申请事项会议-更新")
    @ApiOperation(value = "申请事项会议-更新")
    @PostMapping(value = "updateSqsxHy")
    public HttpResult updateSqsxHy(@RequestBody HashMap<String,String> buffer) throws IllegalAccessException, InvocationTargetException {

        String id = buffer.get("id");
        if (StringUtils.isBlank(id)){
            return HttpResult.error("参数为空！");
        }

        SpcySqsxHyzt updateBean = spcySqsxHyztService.getById(id);
        if (updateBean == null){
            return HttpResult.error("没有相匹配数据！");
        }

        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(updateBean);

        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(updateBean, buffer);

        updateBean.setUpdateTime(new Date());
        updateBean.setUpdateBy(GetCurrentUserUtils.getCurrentUserAccount());
        spcySqsxHyztService.updateById(updateBean);

        String operContent = "基本信息修改：";
        operContent += LogUtils.BeanModifyMsg(updateBean,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_SQSX_HY,operContent,updateBean.getFsqsxid(),"申请事项会议-更新", SpcyConstant.LOGS_SYS_TYPE_XG);


        return HttpResultVo.HttpResultSave(id, "保存成功");
    }

    @Log(title = "申请事项会议-删除")
    @ApiOperation(value = "申请事项会议-删除")
    @DeleteMapping(value = "deleteSqsxHy")
    public HttpResult deleteSqsxHy(@RequestParam(value = "ids",defaultValue = "")String ids){
        if (StringUtils.isBlank(ids)){
            return HttpResult.error("参数为空！");
        }

        List<String> idsList = StringPatternUtils.getListByIds(ids);
        List<SpcySqsxHyzt> beanList = spcySqsxHyztService.listByIds(idsList);
        for (SpcySqsxHyzt bean : beanList) {

            spcySqsxHyztService.removeById(bean.getId());

            /** 删除会议明细信息 */
            List<SpcySqsxHymx> mxList = spcySqsxHymxService.list(new LambdaQueryWrapper<SpcySqsxHymx>()
                    .eq(SpcySqsxHymx::getFhyid, bean.getId()));
            if (CollectionUtil.isNotEmpty(mxList)) {
                spcySqsxHymxService.remove(new LambdaQueryWrapper<SpcySqsxHymx>().eq(SpcySqsxHymx::getFhyid, bean.getId()));

                for (int i = 0; i < mxList.size(); i++) {
                    if (StringUtils.isBlank(mxList.get(i).getFuserid())){
                        zdyUploadFileService.deleteFileByBatch(mxList.get(i).getId());
                    }
                }
            }

            String operContent = "删除：";
            operContent += LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(bean));

            spcyLogService.addLogs(LogConstant.LOGS_SQSX_HY, operContent, bean.getFsqsxid(), "申请事项会议-删除", SpcyConstant.LOGS_SYS_TYPE_SC);
        }

        return HttpResult.ok("删除成功");
    }

//    @Log(title = "申请事项会议明细-添加")
//    @ApiOperation(value = "申请事项会议明细-添加")
    @PostMapping(value = "addSqsxHymx")
    public HttpResult addSqsxHymx(@RequestBody SpcySqsxHymx bean){
        if (StringUtils.isBlank(bean.getFhyid())){
            return HttpResult.error("参数为空！");
        }
        if (StringUtils.isBlank(bean.getFxm())){
            return HttpResult.error("姓名为空！");
        }

        bean.setId(GetUuIdUtils.ReplaceUuId());
        spcySqsxHymxService.save(bean);

        String operContent = "删除：";
        operContent += LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(bean));

        spcyLogService.addLogs(LogConstant.LOGS_SQSX_HY,operContent,bean.getFhyid(),"申请事项会议明细-添加", SpcyConstant.LOGS_SYS_TYPE_SC);

        return HttpResultVo.HttpResultSave(bean, "添加成功");
    }

//    @Log(title = "申请事项会议明细-更新")
//    @ApiOperation(value = "申请事项会议明细-更新")
    @PostMapping(value = "updateSqsxHymx")
    public HttpResult updateSqsxHymx(@RequestBody HashMap<String,String> buffer) throws IllegalAccessException, InvocationTargetException {

        String id = buffer.get("id");
        if (StringUtils.isBlank(id)){
            return HttpResult.error("参数为空！");
        }

        SpcySqsxHymx updateBean = spcySqsxHymxService.getById(id);
        if (updateBean == null){
            throw new BusinessException("没有相匹配数据！");
        }

        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(updateBean);

        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(updateBean, buffer);

        updateBean.setUpdateTime(new Date());
        updateBean.setUpdateBy(GetCurrentUserUtils.getCurrentUserAccount());
        spcySqsxHymxService.updateById(updateBean);

        String operContent = "基本信息修改：";
        operContent += LogUtils.BeanModifyMsg(updateBean,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_SQSX_HY,operContent,updateBean.getFhyid(),"申请事项会议明细-更新", SpcyConstant.LOGS_SYS_TYPE_XG);


        return HttpResultVo.HttpResultSave(updateBean, "保存成功");
    }

    @Log(title = "申请事项会议明细-删除")
    @ApiOperation(value = "申请事项会议明细-删除")
    @DeleteMapping(value = "deleteSqsxHymx")
    public HttpResult deleteSqsxHymx(@RequestParam(value = "ids",defaultValue = "")String ids){
        if (StringUtils.isBlank(ids)){
            return HttpResult.error("参数为空！");
        }

        List<String> idsList = StringPatternUtils.getListByIds(ids);
        List<SpcySqsxHymx> mxList = spcySqsxHymxService.listByIds(idsList);
        for (SpcySqsxHymx bean : mxList) {

            spcySqsxHymxService.removeById(bean.getId());

            if (StringUtils.isBlank(bean.getFuserid())) {
                zdyUploadFileService.deleteFileByBatch(bean.getId());
            }

            String operContent = "删除：";
            operContent += LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(bean));

            spcyLogService.addLogs(LogConstant.LOGS_SQSX_HY, operContent, bean.getFhyid(), "申请事项会议-删除", SpcyConstant.LOGS_SYS_TYPE_SC);
        }

        return HttpResult.ok("删除成功");
    }

    @Log(title = "判断会议是否存在缺席情况")
    @ApiOperation(value = "判断会议是否存在缺席情况")
    @GetMapping(value = "hyqxqk")
    public HttpResult hyqxqk(@RequestParam(value = "sqsxid",defaultValue = "") String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("参数为空！");
        }

        List<String> list = spcySqsxHyztService.selectHyQxqksmByFsqsxid(sqsxid);
        if (CollectionUtil.isNotEmpty(list)){
            return HttpResultVo.HttpResultGet(1);
        }

        return HttpResultVo.HttpResultGet(0);
    }

}
